package quick.start.core.json;

import com.google.gson.*;

import java.lang.reflect.Type;

public class FastActivator<TEntity> implements JsonDeserializer<TEntity>, JsonSerializer<TEntity> {
	private static final String CLASS_META_KEY = "CLASS_META_KEY";

	@Override
	public JsonElement serialize(TEntity src, Type typeOfSrc, JsonSerializationContext context) {
		JsonElement element = context.serialize(src, src.getClass());
		element.getAsJsonObject().addProperty(CLASS_META_KEY, src.getClass().getCanonicalName());
		return element;
	}

	@Override
	public TEntity deserialize(JsonElement json, Type typeOfEntity, JsonDeserializationContext context) throws JsonParseException {
		JsonObject jsonObj = json.getAsJsonObject();
		String className = jsonObj.get(CLASS_META_KEY).getAsString();
		try{
			Class<?> clz = Class.forName(className);
			return (TEntity) context.deserialize(json, clz);
		}catch(ClassNotFoundException e){
			throw new JsonParseException(e);
		}
	}
}
